//
//  WBComposeViewController.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/11.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeViewController: UIViewController {
    
    private lazy var titleLabel: UILabel = {
       
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        
        if let name = WBUserAccountViewModel.sharedViewModel.userAccount?.name {
            
            let content = "发微博\n\(name)"
            
            let attributedStr:NSMutableAttributedString = NSMutableAttributedString(string: content)
            
            let range = (content as NSString).range(of: name)
            
            attributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.orange], range: range)
            
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        
        return label
    }()
    
    // MARK: --表情键盘
    fileprivate lazy var emoticonKeyBoard:WBEmoticonKeyBoard = {
       
        let keyBoard = WBEmoticonKeyBoard(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
        
        return keyBoard
    }()

    fileprivate lazy var sendButton :UIButton = {
       
        let button = UIButton()
        
        button.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        
        button.setTitle("发送", for: .normal)
        
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.frame.size = CGSize(width: 45, height: 35)

        return button
    }()
    // MARK: --发送按钮点击事件
    @objc private func sendButtonAction() {
        
        let token = WBUserAccountViewModel.sharedViewModel.accessToken!
        
        let text = textView.emoticonText
        
        SVProgressHUD.show()
        
        if pictureView.imageArray.count > 0 {
            
            let image  = pictureView.imageArray.first!
            
            WBNetworkTools.sharedTools.sendMessage(token: token, status: text, pic: image, callBack: { (response, error) in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
        } else {
            
            WBNetworkTools.sharedTools.sendMessage(token: token, status: text, callBack: { (response, error) in
                
                if error != nil {
                    
                    SVProgressHUD.showError(withStatus: "发送失败")
                    
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
            
        }
    
    }
    
    fileprivate lazy var textView: WBComposeTextView = {
       
        let textView = WBComposeTextView()
        
        textView.delegate = self
        
        textView.placHolder = "请输入微博内容~"
        
        textView.font = UIFont.systemFont(ofSize: 20)
        
        // 垂直方向拖动
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    fileprivate lazy var toolBar: WBComposeToolBar = WBComposeToolBar()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        setupUI()
        
    }
    
    // MARK: --
    
    fileprivate lazy var pictureView: WBComposePictureView = {
        
        let collectionView = WBComposePictureView()
        
        collectionView.backgroundColor = self.textView.backgroundColor
        
        return collectionView
    }()

    private func setupUI() {
        // 监听键盘弹出
        NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 监听表情按钮
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmoticonButtonAction(noti:)), name: NSNotification.Name(ClickEmotionButtonNotificationName), object: nil)
        // 监听删除按钮
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmoticonDeleteButton), name: NSNotification.Name(ClickDeleteButtonNotificationName), object: nil)
        
        setupNav()
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        textView.snp.makeConstraints { (make) in
            
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        toolBar.snp.makeConstraints { (make) in
            
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(35)
        }
        
        pictureView.snp.makeConstraints { (make) in
            
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp.width).offset(-20)
        }
        
        toolBar.callBack = {[weak self] (type:WBComposeToolBarType)->() in
            
            switch type {
            case .pictue:
                print("图片")
                self?.pictureButtonAction()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.emoticonButtonAction()
            case .add:
                print("加号")
                
            }

        }
       
        pictureView.addPictureCallBack = {[weak self] in
            
            self?.pictureButtonAction()
        }
        
    }

    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, action: #selector(cancelAction), title: "取消", imageName: nil)
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
        
    }
    
    @objc private func cancelAction() {
        // 辞去第一响应者
        textView.resignFirstResponder()
        self.dismiss(animated: true, completion: nil)
        
    }
    // MARK: --点击删除按钮发生的通知
    @objc private func clickEmoticonDeleteButton() {
        
        textView.deleteBackward()
    }
    // MARK: --点击表情按钮发送的通知
    @objc private func clickEmoticonButtonAction(noti:Notification) {
        
        let emoticon = noti.object as! WBEmoticon
        
        textView.insertEmoticon(emticon: emoticon)
        
        WBEmoticonTools.sharedTools.saveRecentEmoticon(emoticon: emoticon) { 
            
            self.emoticonKeyBoard.reloadRecentData()
        }
        
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func KeyboardWillChangeFrame(noti:Notification) {
        
        let keyBoarFrame = noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        print(keyBoarFrame)
        
        toolBar.snp.updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(keyBoarFrame.origin.y - ScreenHeight)
        }
        
        UIView.animate(withDuration: 0.25) { 
            
            self.view.layoutIfNeeded()
        }
        
    }
}

// MARK: --UITextViewDelegate的代理方法
extension WBComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        // 让textView失去第一响应者
        // 结束编辑就是失去第一响应者
        self.view.endEditing(true)
    }
}


// MARK: --处理toolbar按钮点击事件
extension WBComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func emoticonButtonAction() {
        
        if textView.inputView == nil {
            
            textView.inputView = emoticonKeyBoard
            
            toolBar.switchButtonIcon(isEmoticonKeyBoard: true)
        } else {
            
            textView.inputView = nil
            
            toolBar.switchButtonIcon(isEmoticonKeyBoard: false)
        }
        
        // 成为第一响应者
        textView.becomeFirstResponder()
        // 重新加载自定义输入视图
        textView.reloadInputViews()
    }
    
    //图片按钮点击处理
    func pictureButtonAction() {
        
        let imagePickCtr = UIImagePickerController()
        imagePickCtr.delegate = self
        
        // 判断来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            
            imagePickCtr.sourceType = .camera
        } else {
            
            imagePickCtr.sourceType = .photoLibrary
        }
        
        self.present(imagePickCtr, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //  获取原始图片UIImagePickerControllerOriginalImage， 获取编辑图片的key: UIImagePickerControllerEditedImage 字符串
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let currimage = scaleImage(scaleWidth: 200, image: image)
        
        pictureView.show(image: currimage)
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    private func scaleImage(scaleWidth:CGFloat, image:UIImage) -> UIImage {
        // 计算宽高比
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        // 开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        // 把图片压缩到指定区域内
        let range = CGRect(origin: CGPoint.zero, size: scaleSize)
        image.draw(in: range)
        // 在图片上下文中获取压缩后的图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        // 结束图片上下文
        UIGraphicsEndImageContext()
        return currentImage!
        
    }
    
}
